package org.linlinjava.litemall.admin.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.dto.ArticleRecord;
import org.linlinjava.litemall.admin.service.AdminArticlesService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallArticles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/articles")
@Validated
public class PiccArticlesController {
    private final Log logger = LogFactory.getLog(PiccArticlesController.class);

    @Autowired
    private AdminArticlesService adminArticlesService;

    /**
     * 后台管理发布文章的路由
     * @param record
     * @return 已经发布的文章
     */
    @RequiresPermissions("admin:articles:create")
    @RequiresPermissionsDesc(menu = {"文章管理", "发布文章"}, button = "发布")
    @PostMapping("/create")
    public Object create(@RequestBody ArticleRecord record) {
        LitemallArticles article = adminArticlesService.create(record);
        return ResponseUtil.ok(article);
    }

    /**
     * 查询所有文章记录的路由
     * @param page
     * @param limit
     * @param deleted
     * @param sort
     * @return 返回联合查询的结果，联合了storage中header表中的url和type
     */
    @RequiresPermissions("admin:articles:list")
    @RequiresPermissionsDesc(menu = {"文章管理", "所有文章"}, button = "查询")
    @GetMapping("/list")
    public Object list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @RequestParam(defaultValue = "0") Integer deleted,
                       @RequestParam(defaultValue = "update_time") String sort) {
        return adminArticlesService.list(deleted, page, limit, sort);
    }

    @RequiresPermissions("admin:articles:delete")
    @RequiresPermissionsDesc(menu = {"文章管理", "删除文章"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestParam Integer id) {
        adminArticlesService.delete(id);
        return ResponseUtil.ok();
    }
}
